/**
 * 游戏管理器
 * 负责游戏状态管理、场景切换和主要游戏逻辑
 */

import { GAME_CONSTANTS, DIRECTIONS, KEY_BINDINGS, DEFAULT_GAME_STATE } from './constants.js';
import { MathUtils, DOMUtils, GameUtils, NotificationUtils, PerformanceUtils, StorageUtils, DebugUtils } from './utils.js';
import { Player, Monster, Item } from './game-objects.js';
import { ALL_ITEMS, getItemsByType } from './data.js';

/**
 * 游戏管理器类
 */
export class GameManager {
    constructor() {
        this.canvas = null;
        this.ctx = null;
        this.gameState = { ...DEFAULT_GAME_STATE };
        this.keys = {};
        this.isRunning = false;
        this.lastFrameTime = 0;
        this.deltaTime = 0;
        
        // 游戏对象管理
        this.player = null;
        this.monsters = [];
        this.items = [];
        this.currentMap = null;
        this.mapManager = null;
        
        // UI管理
        this.uiManager = null;
        
        // 性能监控
        this.performanceMonitor = PerformanceUtils.fpsCounter;
        
        // 初始化
        this.init();
    }

    /**
     * 初始化游戏
     */
    async init() {
        try {
            DebugUtils.log('开始初始化游戏管理器');
            
            this.setupCanvas();
            this.setupEventListeners();
            await this.loadGameAssets();
            this.initializeGameObjects();
            this.setupUI();
            
            DebugUtils.log('游戏管理器初始化完成');
        } catch (error) {
            DebugUtils.error('游戏初始化失败', error);
            throw error;
        }
    }

    /**
     * 设置画布
     */
    setupCanvas() {
        this.canvas = DOMUtils.getElement('#gameCanvas');
        if (!this.canvas) {
            throw new Error('无法找到游戏画布');
        }
        
        this.ctx = this.canvas.getContext('2d');
        if (!this.ctx) {
            throw new Error('无法获取2D渲染上下文');
        }
        
        this.resizeCanvas();
        window.addEventListener('resize', () => this.resizeCanvas());
        
        DebugUtils.log('画布设置完成', {
            width: this.canvas.width,
            height: this.canvas.height
        });
    }

    /**
     * 调整画布大小
     */
    resizeCanvas() {
        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight;
        
        DebugUtils.log('画布大小已调整', {
            width: this.canvas.width,
            height: this.canvas.height
        });
    }

    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        // 键盘事件
        document.addEventListener('keydown', (e) => this.onKeyDown(e));
        document.addEventListener('keyup', (e) => this.onKeyUp(e));
        
        // 鼠标事件
        this.canvas.addEventListener('click', (e) => this.onCanvasClick(e));
        this.canvas.addEventListener('contextmenu', (e) => e.preventDefault());
        
        // 窗口事件
        window.addEventListener('blur', () => this.onWindowBlur());
        window.addEventListener('focus', () => this.onWindowFocus());
        
        DebugUtils.log('事件监听器设置完成');
    }

    /**
     * 加载游戏资源
     */
    async loadGameAssets() {
        try {
            // 这里可以加载精灵图、音频等资源
            // 目前使用简单的色块渲染，所以暂时跳过
            
            // 加载地图管理器
            if (window.MapManager) {
                this.mapManager = new window.MapManager();
                DebugUtils.log('地图管理器加载完成');
            } else {
                throw new Error('MapManager未找到');
            }
            
            DebugUtils.log('游戏资源加载完成');
        } catch (error) {
            DebugUtils.error('资源加载失败', error);
            throw error;
        }
    }

    /**
     * 初始化游戏对象
     */
    initializeGameObjects() {
        // 初始化玩家
        this.player = new Player(100, 100, this.gameState);
        
        // 初始化当前地图
        if (this.mapManager) {
            const currentMapData = this.mapManager.getCurrentMap();
            DebugUtils.log('当前地图数据:', currentMapData);
            
            if (currentMapData) {
                this.currentMap = new GameMap(currentMapData);
                this.currentMap.generate();
                
                // 设置玩家出生点
                const spawnPoint = this.currentMap.getSpawnPoint();
                if (spawnPoint) {
                    this.player.x = spawnPoint.x * GAME_CONSTANTS.TILE_SIZE;
                    this.player.y = spawnPoint.y * GAME_CONSTANTS.TILE_SIZE;
                }
            } else {
                DebugUtils.error('无法获取地图数据');
                // 使用默认地图数据
                this.createDefaultMap();
            }
        } else {
            DebugUtils.error('MapManager未初始化');
            // 使用默认地图数据
            this.createDefaultMap();
        }
        
        // 初始化相机
        this.gameState.camera = {
            x: this.player.x - this.canvas.width / 2,
            y: this.player.y - this.canvas.height / 2
        };
        
        DebugUtils.log('游戏对象初始化完成');
    }

    /**
     * 创建默认地图
     */
    createDefaultMap() {
        const defaultMapData = {
            id: 'default',
            name: '测试地图',
            level: 1,
            description: '默认测试地图',
            size: { width: 40, height: 40 },
            monsterTypes: ['SLIME'],
            monsterLevelRange: [1, 3],
            monsterCount: 5,
            spawnRate: 0.008,
            itemDropRate: 0.6,
            background: '#2d5016',
            difficulty: 'easy',
            tileTypes: {
                grass: { color: '#4CAF50', walkable: true },
                tree: { color: '#2E7D32', walkable: false },
                water: { color: '#2196F3', walkable: false },
                rock: { color: '#795548', walkable: false }
            },
            portals: []
        };
        
        this.currentMap = new GameMap(defaultMapData);
        this.currentMap.generate();
        DebugUtils.log('使用默认地图数据');
    }

    /**
     * 设置UI
     */
    setupUI() {
        // 确保DOM已加载
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => {
                this.initializeUI();
            });
        } else {
            this.initializeUI();
        }
    }

    /**
     * 初始化UI
     */
    initializeUI() {
        DebugUtils.log('开始初始化UI');
        
        // 验证UI元素是否存在
        this.verifyUIElements();
        
        // 强制初始化所有面板为隐藏状态
        this.initializePanelStates();
        
        // 创建背包槽位
        this.createInventorySlots();
        
        // 设置UI事件处理器
        this.setupUIHandlers();
        
        // 更新UI显示
        this.updateUI();
        
        DebugUtils.log('UI初始化完成');
    }

    /**
     * 初始化面板状态
     */
    initializePanelStates() {
        DebugUtils.log('初始化面板状态');
        const allPanels = ['inventory-panel', 'character-panel', 'skills-panel', 'map-panel'];
        
        allPanels.forEach(panelId => {
            const panel = DOMUtils.getElement(`#${panelId}`);
            if (panel) {
                // 强制设置为隐藏状态
                panel.classList.add('hidden');
                panel.classList.remove('force-show');
                panel.style.cssText = 'display: none !important; visibility: hidden !important; opacity: 0 !important;';
                DebugUtils.log(`面板 ${panelId} 初始化为隐藏状态`);
            }
        });
    }

    /**
     * 验证UI元素是否存在
     */
    verifyUIElements() {
        const requiredElements = [
            '#inventory-button',
            '#character-button', 
            '#skills-button',
            '#map-button',
            '#inventory-panel',
            '#character-panel',
            '#skills-panel',
            '#map-panel'
        ];
        
        requiredElements.forEach(selector => {
            const element = document.querySelector(selector);
            if (element) {
                DebugUtils.log(`✅ 找到元素: ${selector}`);
            } else {
                DebugUtils.error(`❌ 未找到元素: ${selector}`);
            }
        });
    }

    /**
     * 键盘按下事件
     * @param {KeyboardEvent} event 
     */
    onKeyDown(event) {
        this.keys[event.key] = true;
        
        // 处理UI快捷键
        this.handleUIShortcuts(event.key);
        
        // 处理技能快捷键
        this.handleSkillShortcuts(event.key);
    }

    /**
     * 键盘释放事件
     * @param {KeyboardEvent} event 
     */
    onKeyUp(event) {
        this.keys[event.key] = false;
    }

    /**
     * 画布点击事件
     * @param {MouseEvent} event 
     */
    onCanvasClick(event) {
        const rect = this.canvas.getBoundingClientRect();
        const x = event.clientX - rect.left;
        const y = event.clientY - rect.top;
        
        // 转换为世界坐标
        const worldX = x + this.gameState.camera.x;
        const worldY = y + this.gameState.camera.y;
        
        DebugUtils.log('画布点击', { worldX, worldY });
    }

    /**
     * 窗口失焦事件
     */
    onWindowBlur() {
        // 清空所有按键状态
        this.keys = {};
        DebugUtils.log('窗口失去焦点，清空按键状态');
    }

    /**
     * 窗口获得焦点事件
     */
    onWindowFocus() {
        DebugUtils.log('窗口获得焦点');
    }

    /**
     * 处理UI快捷键
     * @param {string} key 
     */
    handleUIShortcuts(key) {
        if (KEY_BINDINGS.TOGGLE_INVENTORY.includes(key)) {
            this.togglePanel('inventory-panel');
        } else if (KEY_BINDINGS.TOGGLE_CHARACTER.includes(key)) {
            this.togglePanel('character-panel');
        } else if (KEY_BINDINGS.TOGGLE_SKILLS.includes(key)) {
            this.togglePanel('skills-panel');
        } else if (KEY_BINDINGS.TOGGLE_MAP.includes(key)) {
            this.togglePanel('map-panel');
        } else if (KEY_BINDINGS.CLOSE_PANELS.includes(key)) {
            this.closeAllPanels();
        }
    }

    /**
     * 处理技能快捷键
     * @param {string} key 
     */
    handleSkillShortcuts(key) {
        if (KEY_BINDINGS.SKILL_1.includes(key)) {
            this.castSkill('fireball');
        } else if (KEY_BINDINGS.SKILL_2.includes(key)) {
            this.castSkill('heal');
        } else if (KEY_BINDINGS.SKILL_3.includes(key)) {
            this.castSkill('lightning');
        }
    }

    /**
     * 开始游戏循环
     */
    start() {
        if (this.isRunning) return;
        
        this.isRunning = true;
        this.lastFrameTime = performance.now();
        this.gameLoop(this.lastFrameTime);
        
        DebugUtils.log('游戏循环已开始');
    }

    /**
     * 停止游戏循环
     */
    stop() {
        this.isRunning = false;
        DebugUtils.log('游戏循环已停止');
    }

    /**
     * 游戏主循环
     * @param {number} currentTime 
     */
    gameLoop(currentTime) {
        if (!this.isRunning) return;
        
        // 计算帧时间
        this.deltaTime = currentTime - this.lastFrameTime;
        this.lastFrameTime = currentTime;
        
        // 更新性能监控
        this.performanceMonitor.update(currentTime);
        
        // 游戏逻辑更新
        this.update(this.deltaTime);
        
        // 渲染
        this.render();
        
        // 请求下一帧
        requestAnimationFrame((time) => this.gameLoop(time));
    }

    /**
     * 游戏逻辑更新
     * @param {number} deltaTime 
     */
    update(deltaTime) {
        // 更新玩家
        this.updatePlayer(deltaTime);
        
        // 更新怪物
        this.updateMonsters(deltaTime);
        
        // 更新物品
        this.updateItems(deltaTime);
        
        // 更新相机
        this.updateCamera();
        
        // 检查碰撞
        this.checkCollisions();
        
        // 检查传送门
        this.checkPortalInteraction();
        
        // 生成怪物
        this.spawnMonsters();
        
        // 更新UI
        this.updateUI();
    }

    /**
     * 更新玩家
     * @param {number} deltaTime 
     */
    updatePlayer(deltaTime) {
        if (!this.player) return;
        
        // 处理移动输入
        let deltaX = 0;
        let deltaY = 0;
        
        if (this.isKeyPressed(KEY_BINDINGS.MOVE_UP)) {
            deltaY = -1;
        }
        if (this.isKeyPressed(KEY_BINDINGS.MOVE_DOWN)) {
            deltaY = 1;
        }
        if (this.isKeyPressed(KEY_BINDINGS.MOVE_LEFT)) {
            deltaX = -1;
        }
        if (this.isKeyPressed(KEY_BINDINGS.MOVE_RIGHT)) {
            deltaX = 1;
        }
        
        // 移动玩家
        if (deltaX !== 0 || deltaY !== 0) {
            this.player.move(deltaX, deltaY, this.currentMap);
        } else {
            this.player.stopMoving();
        }
        
        // 更新玩家状态
        this.player.update(deltaTime);
    }

    /**
     * 更新怪物
     * @param {number} deltaTime 
     */
    updateMonsters(deltaTime) {
        this.monsters = this.monsters.filter(monster => {
            if (!monster.active) {
                return false;
            }
            
            monster.update(deltaTime, this.player);
            return true;
        });
    }

    /**
     * 更新物品
     * @param {number} deltaTime 
     */
    updateItems(deltaTime) {
        this.items.forEach(item => {
            item.update(deltaTime);
        });
    }

    /**
     * 更新相机
     */
    updateCamera() {
        if (!this.player) return;
        
        const targetX = this.player.x - this.canvas.width / 2;
        const targetY = this.player.y - this.canvas.height / 2;
        
        // 平滑相机跟随
        this.gameState.camera.x = MathUtils.lerp(
            this.gameState.camera.x, 
            targetX, 
            0.1
        );
        this.gameState.camera.y = MathUtils.lerp(
            this.gameState.camera.y, 
            targetY, 
            0.1
        );
    }

    /**
     * 检查碰撞
     */
    checkCollisions() {
        if (!this.player) return;
        
        // 检查怪物碰撞
        this.monsters.forEach((monster, index) => {
            if (this.player.checkCollision(monster)) {
                this.handlePlayerMonsterCollision(this.player, monster, index);
            }
        });
        
        // 检查物品碰撞
        this.items.forEach((item, index) => {
            if (this.player.checkCollision(item)) {
                this.handlePlayerItemCollision(this.player, item, index);
            }
        });
    }

    /**
     * 处理玩家与怪物的碰撞
     * @param {Player} player 
     * @param {Monster} monster 
     * @param {number} index 
     */
    handlePlayerMonsterCollision(player, monster, index) {
        if (player.inCombat) return;
        
        player.inCombat = true;
        
        // 玩家攻击怪物
        const damageToMonster = monster.takeDamage(player.damage);
        DebugUtils.log(`玩家攻击 ${monster.name}，造成 ${damageToMonster} 点伤害`);
        
        // 怪物攻击玩家
        const damageToPlayer = player.takeDamage(monster.damage);
        DebugUtils.log(`${monster.name} 攻击玩家，造成 ${damageToPlayer} 点伤害`);
        
        // 检查怪物是否死亡
        if (!monster.active) {
            this.handleMonsterDefeat(monster);
            this.monsters.splice(index, 1);
        }
        
        // 重置战斗状态
        setTimeout(() => {
            player.inCombat = false;
        }, GAME_CONSTANTS.COMBAT_COOLDOWN);
    }

    /**
     * 处理玩家与物品的碰撞
     * @param {Player} player 
     * @param {Item} item 
     * @param {number} index 
     */
    handlePlayerItemCollision(player, item, index) {
        if (!item.pickupable) return;
        
        DebugUtils.log(`拾取物品: ${item.name}`);
        
        // 尝试自动装备
        if (['weapon', 'armor', 'accessory'].includes(item.type)) {
            if (this.autoEquipItem(player, item)) {
                this.items.splice(index, 1);
                return;
            }
        }
        
        // 添加到背包
        if (player.inventory.length < GAME_CONSTANTS.INVENTORY_SIZE) {
            player.inventory.push(item);
            this.items.splice(index, 1);
            this.updateInventoryDisplay();
            NotificationUtils.showNotification(`拾取了 ${item.name}`, 'success');
        } else {
            NotificationUtils.showNotification('背包已满', 'warning');
        }
    }

    /**
     * 处理怪物被击败
     * @param {Monster} monster 
     */
    handleMonsterDefeat(monster) {
        // 获得经验值
        this.player.gainExp(monster.exp);
        
        // 掉落物品
        if (Math.random() < monster.dropRate) {
            this.dropItem(monster.x, monster.y);
        }
        
        NotificationUtils.showNotification(
            `击败了 ${monster.name}，获得 ${monster.exp} 经验值`, 
            'success'
        );
    }

    /**
     * 掉落物品
     * @param {number} x 
     * @param {number} y 
     */
    dropItem(x, y) {
        const availableItems = Object.values(ALL_ITEMS);
        const randomItem = availableItems[Math.floor(Math.random() * availableItems.length)];
        
        const item = new Item(
            x + (Math.random() - 0.5) * GAME_CONSTANTS.TILE_SIZE * 2,
            y + (Math.random() - 0.5) * GAME_CONSTANTS.TILE_SIZE * 2,
            { ...randomItem }
        );
        
        this.items.push(item);
        DebugUtils.log(`掉落物品: ${item.name}`);
    }

    /**
     * 生成怪物
     */
    spawnMonsters() {
        if (!this.mapManager || !this.currentMap) return;
        
        const currentMapData = this.mapManager.getCurrentMap();
        const maxMonsters = currentMapData.monsterCount || 10;
        
        if (this.monsters.length < maxMonsters && Math.random() < currentMapData.spawnRate) {
            const spawnPoint = this.currentMap.getSpawnPoint();
            if (spawnPoint) {
                const monsterTypes = currentMapData.monsterTypes;
                const randomType = monsterTypes[Math.floor(Math.random() * monsterTypes.length)];
                const levelRange = currentMapData.monsterLevelRange;
                const level = Math.floor(Math.random() * (levelRange[1] - levelRange[0] + 1)) + levelRange[0];
                
                const monster = new Monster(
                    spawnPoint.x * GAME_CONSTANTS.TILE_SIZE + Math.random() * GAME_CONSTANTS.TILE_SIZE,
                    spawnPoint.y * GAME_CONSTANTS.TILE_SIZE + Math.random() * GAME_CONSTANTS.TILE_SIZE,
                    randomType,
                    level
                );
                
                this.monsters.push(monster);
                DebugUtils.log(`生成怪物: ${monster.name} Lv.${monster.level}`);
            }
        }
    }

    /**
     * 检查传送门交互
     */
    checkPortalInteraction() {
        if (!this.mapManager || !this.currentMap || !this.player) return;
        
        const portal = this.currentMap.checkPortal(this.player.x, this.player.y);
        if (portal) {
            const targetMapData = this.mapManager.maps.get(portal.targetMap);
            if (targetMapData && this.player.level >= targetMapData.level - 1) {
                this.switchMap(portal.targetMap);
            } else {
                NotificationUtils.showNotification(
                    `等级不足，无法进入 ${targetMapData?.name}`, 
                    'warning'
                );
            }
        }
    }

    /**
     * 切换地图
     * @param {string} mapId 
     */
    switchMap(mapId) {
        const newPosition = this.mapManager.switchMap(mapId);
        if (newPosition) {
            // 清空当前怪物和物品
            this.monsters = [];
            this.items = [];
            
            // 创建新地图
            const newMapData = this.mapManager.getCurrentMap();
            this.currentMap = new GameMap(newMapData);
            this.currentMap.generate();
            
            // 设置玩家位置
            this.player.x = newPosition.x;
            this.player.y = newPosition.y;
            
            NotificationUtils.showNotification(`传送到: ${newMapData.name}`, 'info');
            DebugUtils.log(`切换到地图: ${newMapData.name}`);
        }
    }

    /**
     * 渲染游戏
     */
    render() {
        // 清空画布
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // 保存上下文状态
        this.ctx.save();
        
        // 应用相机变换
        this.ctx.translate(-this.gameState.camera.x, -this.gameState.camera.y);
        
        // 绘制地图
        if (this.currentMap) {
            this.currentMap.draw(this.ctx, this.gameState.camera);
        }
        
        // 绘制物品
        this.items.forEach(item => item.render(this.ctx, this.gameState.camera));
        
        // 绘制怪物
        this.monsters.forEach(monster => monster.render(this.ctx, this.gameState.camera));
        
        // 绘制玩家
        if (this.player) {
            this.player.render(this.ctx, this.gameState.camera);
        }
        
        // 恢复上下文状态
        this.ctx.restore();
        
        // 绘制UI（不受相机影响）
        this.renderUI();
    }

    /**
     * 渲染UI
     */
    renderUI() {
        // UI渲染逻辑（如果需要在canvas上绘制UI元素）
        // 目前主要使用HTML/CSS UI
    }

    /**
     * 检查按键是否被按下
     * @param {array} keyList 
     * @returns {boolean}
     */
    isKeyPressed(keyList) {
        return keyList.some(key => this.keys[key]);
    }

    /**
     * 使用技能
     * @param {string} skillName 
     */
    castSkill(skillName) {
        if (!this.player) return;
        
        // 寻找最近的敌人作为目标
        let target = null;
        if (skillName !== 'heal') {
            target = this.findNearestMonster();
        }
        
        this.player.useSkill(skillName, target);
    }

    /**
     * 寻找最近的怪物
     * @returns {Monster|null}
     */
    findNearestMonster() {
        if (!this.player || this.monsters.length === 0) return null;
        
        let nearestMonster = null;
        let nearestDistance = Infinity;
        
        this.monsters.forEach(monster => {
            const distance = MathUtils.distance(
                this.player.x, this.player.y,
                monster.x, monster.y
            );
            
            if (distance < nearestDistance && distance < GAME_CONSTANTS.SKILL_RANGE) {
                nearestDistance = distance;
                nearestMonster = monster;
            }
        });
        
        return nearestMonster;
    }

    /**
     * 自动装备物品
     * @param {Player} player 
     * @param {Item} item 
     * @returns {boolean}
     */
    autoEquipItem(player, item) {
        // 这里实现自动装备逻辑
        // 简化版本，具体实现可以参考原来的autoEquipItem函数
        return false;
    }

    /**
     * 显示面板
     * @param {string} panelId 
     */
    showPanel(panelId) {
        DebugUtils.log(`显示面板: ${panelId}`);
        const panel = DOMUtils.getElement(`#${panelId}`);
        if (!panel) {
            DebugUtils.error(`未找到面板: ${panelId}`);
            return;
        }

        // 先关闭其他面板
        this.closeOtherPanels(panelId);
        
        // 移除所有可能的隐藏类和样式
        panel.classList.remove('hidden');
        panel.classList.add('force-show');
        
        // 完全重置样式，确保显示
        panel.removeAttribute('style');
        panel.style.cssText = `
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            z-index: 9999 !important;
            position: absolute !important;
            top: 50% !important;
            left: 50% !important;
            transform: translate(-50%, -50%) !important;
            width: ${panelId === 'map-panel' || panelId === 'character-panel' ? '700px' : '800px'} !important;
            height: 600px !important;
            background: linear-gradient(135deg, rgba(18, 23, 37, 0.98), rgba(25, 32, 48, 0.95)) !important;
            border-radius: 20px !important;
            color: #e1f5fe !important;
            border: 2px solid #64ffda !important;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5) !important;
            backdrop-filter: blur(10px) !important;
            overflow-y: auto !important;
            pointer-events: auto !important;
        `;
        
        DebugUtils.log(`面板 ${panelId} 已强制设置为显示状态`);
        
        // 立即验证显示结果
        const isVisible = panel.offsetParent !== null && panel.offsetWidth > 0;
        DebugUtils.log(`面板 ${panelId} 立即验证:`, {
            offsetParent: panel.offsetParent,
            offsetWidth: panel.offsetWidth,
            offsetHeight: panel.offsetHeight,
            isVisible: isVisible,
            status: isVisible ? '✅ 显示成功' : '❌ 显示失败'
        });
        
        // 更新面板内容
        if (panelId === 'inventory-panel') {
            this.updateInventoryDisplay();
        } else if (panelId === 'character-panel') {
            this.updateCharacterPanel();
        } else if (panelId === 'map-panel') {
            this.updateMapPanel();
        }
    }

    /**
     * 隐藏面板
     * @param {string} panelId 
     */
    hidePanel(panelId) {
        DebugUtils.log(`隐藏面板: ${panelId}`);
        const panel = DOMUtils.getElement(`#${panelId}`);
        if (!panel) {
            DebugUtils.error(`未找到面板: ${panelId}`);
            return;
        }

        panel.classList.add('hidden');
        panel.classList.remove('force-show');
        panel.removeAttribute('style');
        panel.style.cssText = 'display: none !important; visibility: hidden !important; opacity: 0 !important; pointer-events: none !important;';
        DebugUtils.log(`面板 ${panelId} 已隐藏`);
    }

    /**
     * 切换面板显示状态
     * @param {string} panelId 
     */
    togglePanel(panelId) {
        DebugUtils.log(`尝试切换面板: ${panelId}`);
        const panel = DOMUtils.getElement(`#${panelId}`);
        if (!panel) {
            DebugUtils.error(`未找到面板: ${panelId}`);
            return;
        }

        // 简单判断：如果面板有force-show类，就认为是显示状态
        const isCurrentlyShowing = panel.classList.contains('force-show');
        DebugUtils.log(`面板 ${panelId} 当前显示状态: ${isCurrentlyShowing}`);
        
        if (isCurrentlyShowing) {
            // 如果正在显示，则隐藏
            this.hidePanel(panelId);
        } else {
            // 如果没有显示，则显示
            this.showPanel(panelId);
        }
    }

    /**
     * 关闭其他面板
     * @param {string} currentPanelId 
     */
    closeOtherPanels(currentPanelId) {
        const allPanels = ['inventory-panel', 'character-panel', 'skills-panel', 'map-panel'];
        allPanels.forEach(panelId => {
            if (panelId !== currentPanelId) {
                const panel = DOMUtils.getElement(`#${panelId}`);
                if (panel) {
                    panel.classList.add('hidden');
                    panel.classList.remove('force-show');
                    panel.removeAttribute('style');
                    panel.style.cssText = 'display: none !important; visibility: hidden !important; opacity: 0 !important; pointer-events: none !important;';
                }
            }
        });
    }

    /**
     * 关闭所有面板
     */
    closeAllPanels() {
        const panels = ['inventory-panel', 'character-panel', 'skills-panel', 'map-panel'];
        panels.forEach(panelId => {
            const panel = DOMUtils.getElement(`#${panelId}`);
            if (panel) {
                panel.classList.add('hidden');
                panel.classList.remove('force-show');
                panel.style.display = 'none';
                panel.style.visibility = 'hidden';
                panel.style.opacity = '0';
            }
        });
    }

    /**
     * 创建背包槽位
     */
    createInventorySlots() {
        const inventorySlots = DOMUtils.getElement('#inventory-slots');
        if (!inventorySlots) return;
        
        inventorySlots.innerHTML = '';
        
        for (let i = 0; i < GAME_CONSTANTS.INVENTORY_SIZE; i++) {
            const slot = document.createElement('div');
            slot.className = 'inventory-slot empty';
            slot.id = `slot-${i}`;
            slot.textContent = '-';
            
            slot.addEventListener('click', () => this.onInventorySlotClick(i));
            inventorySlots.appendChild(slot);
        }
    }

    /**
     * 背包槽位点击事件
     * @param {number} slotIndex 
     */
    onInventorySlotClick(slotIndex) {
        if (!this.player || !this.player.inventory[slotIndex]) return;
        
        const item = this.player.inventory[slotIndex];
        
        if (item.type === 'potion') {
            // 使用药水
            if (item.healing) {
                this.player.heal(item.healing);
                this.player.inventory.splice(slotIndex, 1);
                this.updateInventoryDisplay();
                NotificationUtils.showNotification(`使用了 ${item.name}`, 'success');
            }
        }
    }

    /**
     * 设置UI事件处理器
     */
    setupUIHandlers() {
        DebugUtils.log('开始设置UI事件处理器');
        
        // 背包按钮
        const inventoryButton = DOMUtils.getElement('#inventory-button');
        if (inventoryButton) {
            DebugUtils.log('找到背包按钮，设置点击事件');
            inventoryButton.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                DebugUtils.log('背包按钮被点击');
                this.togglePanel('inventory-panel');
            });
        } else {
            DebugUtils.error('未找到背包按钮');
        }
        
        // 角色按钮
        const characterButton = DOMUtils.getElement('#character-button');
        if (characterButton) {
            DebugUtils.log('找到角色按钮，设置点击事件');
            characterButton.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                DebugUtils.log('角色按钮被点击');
                this.togglePanel('character-panel');
            });
        } else {
            DebugUtils.error('未找到角色按钮');
        }
        
        // 技能按钮
        const skillsButton = DOMUtils.getElement('#skills-button');
        if (skillsButton) {
            DebugUtils.log('找到技能按钮，设置点击事件');
            skillsButton.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                DebugUtils.log('技能按钮被点击');
                this.togglePanel('skills-panel');
            });
        } else {
            DebugUtils.error('未找到技能按钮');
        }
        
        // 地图按钮
        const mapButton = DOMUtils.getElement('#map-button');
        if (mapButton) {
            DebugUtils.log('找到地图按钮，设置点击事件');
            mapButton.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                DebugUtils.log('地图按钮被点击');
                this.togglePanel('map-panel');
            });
        } else {
            DebugUtils.error('未找到地图按钮');
        }
        
        // 关闭按钮
        const closeButtons = DOMUtils.getElements('.close-btn');
        DebugUtils.log(`找到 ${closeButtons.length} 个关闭按钮`);
        closeButtons.forEach(button => {
            button.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation();
                const panel = e.target.closest('[id$="-panel"]');
                if (panel) {
                    // 使用强制隐藏方法
                    panel.classList.add('hidden');
                    panel.classList.remove('force-show');
                    panel.style.cssText = 'display: none !important; visibility: hidden !important; opacity: 0 !important;';
                    DebugUtils.log(`关闭面板: ${panel.id}`);
                }
            });
        });
        
        DebugUtils.log('UI事件处理器设置完成');
    }

    /**
     * 更新UI
     */
    updateUI() {
        if (!this.player) return;
        
        // 更新状态条
        this.updateHealthBar();
        this.updateExpBar();
        this.updateManaBar();
        
        // 更新属性显示
        this.updateAttributeDisplay();
        
        // 更新游戏统计
        this.updateGameStats();
        
        // 更新角色面板
        this.updateCharacterPanel();
    }

    /**
     * 更新血条
     */
    updateHealthBar() {
        const healthBar = DOMUtils.getElement('#health-bar');
        const healthText = DOMUtils.getElement('#health-text');
        
        if (healthBar && healthText) {
            const healthPercent = this.player.health / this.player.maxHealth;
            healthBar.style.width = `${healthPercent * 100}%`;
            healthText.textContent = `${this.player.health}/${this.player.maxHealth}`;
        }
    }

    /**
     * 更新经验条
     */
    updateExpBar() {
        const expBar = DOMUtils.getElement('#exp-bar');
        const expText = DOMUtils.getElement('#exp-text');
        
        if (expBar && expText) {
            const expPercent = this.player.exp / this.player.maxExp;
            expBar.style.width = `${expPercent * 100}%`;
            expText.textContent = `${this.player.exp}/${this.player.maxExp}`;
        }
    }

    /**
     * 更新魔法条
     */
    updateManaBar() {
        const manaBar = DOMUtils.getElement('#mana-bar');
        const manaText = DOMUtils.getElement('#mana-text');
        
        if (manaBar && manaText) {
            const manaPercent = this.player.mana / this.player.maxMana;
            manaBar.style.width = `${manaPercent * 100}%`;
            manaText.textContent = `${this.player.mana}/${this.player.maxMana}`;
        }
    }

    /**
     * 更新属性显示
     */
    updateAttributeDisplay() {
        const damageValue = DOMUtils.getElement('#damage-value');
        const defenseValue = DOMUtils.getElement('#defense-value');
        const speedValue = DOMUtils.getElement('#speed-value');
        
        if (damageValue) damageValue.textContent = this.player.damage;
        if (defenseValue) defenseValue.textContent = this.player.defense;
        if (speedValue) speedValue.textContent = this.player.speed;
        
        // 更新等级显示
        const playerLevel = DOMUtils.getElement('.player-level');
        if (playerLevel) {
            playerLevel.textContent = `Lv.${this.player.level}`;
        }
    }

    /**
     * 更新游戏统计
     */
    updateGameStats() {
        const monsterCount = DOMUtils.getElement('#monster-count');
        const itemCount = DOMUtils.getElement('#item-count');
        
        if (monsterCount) monsterCount.textContent = this.monsters.length;
        if (itemCount) itemCount.textContent = this.items.length;
    }

    /**
     * 更新角色面板
     */
    updateCharacterPanel() {
        // 更新角色基本信息
        const charLevel = DOMUtils.getElement('#char-level');
        const charHealth = DOMUtils.getElement('#char-health');
        const charExp = DOMUtils.getElement('#char-exp');
        const charMana = DOMUtils.getElement('#char-mana');
        
        if (charLevel) charLevel.textContent = this.player.level;
        if (charHealth) charHealth.textContent = `${this.player.health}/${this.player.maxHealth}`;
        if (charExp) charExp.textContent = `${this.player.exp}/${this.player.maxExp}`;
        if (charMana) charMana.textContent = `${this.player.mana}/${this.player.maxMana}`;
        
        // 更新详细属性
        const charDamage = DOMUtils.getElement('#char-damage');
        const charDefense = DOMUtils.getElement('#char-defense');
        const charMaxHealth = DOMUtils.getElement('#char-max-health');
        const charSpeed = DOMUtils.getElement('#char-speed');
        const charMaxMana = DOMUtils.getElement('#char-max-mana');
        
        if (charDamage) charDamage.textContent = this.player.damage;
        if (charDefense) charDefense.textContent = this.player.defense;
        if (charMaxHealth) charMaxHealth.textContent = this.player.maxHealth;
        if (charSpeed) charSpeed.textContent = this.player.speed;
        if (charMaxMana) charMaxMana.textContent = this.player.maxMana;
    }

    /**
     * 更新背包显示
     */
    updateInventoryDisplay() {
        for (let i = 0; i < GAME_CONSTANTS.INVENTORY_SIZE; i++) {
            const slot = DOMUtils.getElement(`#slot-${i}`);
            if (slot) {
                if (this.player.inventory[i]) {
                    const item = this.player.inventory[i];
                    slot.className = 'inventory-slot';
                    slot.textContent = item.name;
                    slot.style.background = item.color;
                    slot.title = `${item.name}\n类型: ${item.type}`;
                } else {
                    slot.className = 'inventory-slot empty';
                    slot.textContent = '-';
                    slot.style.background = '';
                    slot.title = '';
                }
            }
        }
    }

    /**
     * 更新地图面板
     */
    updateMapPanel() {
        if (!this.mapManager) return;
        
        const currentMapData = this.mapManager.getCurrentMap();
        if (!currentMapData) return;
        
        // 更新当前地图信息
        const currentMapCard = DOMUtils.getElement('#current-map-card');
        if (currentMapCard) {
            currentMapCard.innerHTML = `
                <div class="map-name">${currentMapData.name}</div>
                <div class="map-level">推荐等级: ${currentMapData.level}</div>
                <div class="map-description">${currentMapData.description}</div>
            `;
        }
        
        // 更新可访问地图列表
        const mapsList = DOMUtils.getElement('#maps-list');
        if (mapsList) {
            mapsList.innerHTML = '';
            const allMaps = this.mapManager.getAllMaps();
            
            allMaps.forEach(map => {
                const mapItem = document.createElement('div');
                mapItem.className = 'map-item';
                
                // 检查地图是否可访问
                const isAccessible = this.player.level >= map.level - 1;
                const isCurrentMap = map.id === this.mapManager.currentMapId;
                
                if (!isAccessible) {
                    mapItem.classList.add('locked');
                }
                
                if (isCurrentMap) {
                    mapItem.style.borderColor = '#4a90e2';
                    mapItem.style.background = 'rgba(74, 144, 226, 0.2)';
                }
                
                mapItem.innerHTML = `
                    <div class="map-item-name">${map.name}</div>
                    <div class="map-item-level">推荐等级: ${map.level}</div>
                    <div class="map-item-description">${map.description}</div>
                `;
                
                // 添加点击事件
                if (isAccessible && !isCurrentMap) {
                    mapItem.addEventListener('click', () => {
                        this.switchMap(map.id);
                        const mapPanel = DOMUtils.getElement('#map-panel');
                        if (mapPanel) {
                            mapPanel.classList.add('hidden');
                        }
                    });
                }
                
                mapsList.appendChild(mapItem);
            });
        }
        
        DebugUtils.log('地图面板更新完成');
    }

    /**
     * 保存游戏
     */
    saveGame() {
        const saveData = {
            player: {
                x: this.player.x,
                y: this.player.y,
                level: this.player.level,
                exp: this.player.exp,
                maxExp: this.player.maxExp,
                health: this.player.health,
                maxHealth: this.player.maxHealth,
                mana: this.player.mana,
                maxMana: this.player.maxMana,
                damage: this.player.damage,
                defense: this.player.defense,
                speed: this.player.speed,
                inventory: this.player.inventory,
                equipment: this.player.equipment
            },
            currentMapId: this.mapManager?.currentMapId,
            timestamp: Date.now()
        };
        
        const success = StorageUtils.save('game_save', saveData);
        if (success) {
            NotificationUtils.showNotification('游戏已保存', 'success');
        } else {
            NotificationUtils.showNotification('保存失败', 'error');
        }
    }

    /**
     * 加载游戏
     */
    loadGame() {
        const saveData = StorageUtils.load('game_save');
        if (!saveData) {
            NotificationUtils.showNotification('没有找到存档', 'warning');
            return false;
        }
        
        try {
            // 恢复玩家数据
            Object.assign(this.player, saveData.player);
            
            // 恢复地图
            if (saveData.currentMapId && this.mapManager) {
                this.switchMap(saveData.currentMapId);
            }
            
            this.updateUI();
            NotificationUtils.showNotification('游戏已加载', 'success');
            return true;
        } catch (error) {
            DebugUtils.error('加载游戏失败', error);
            NotificationUtils.showNotification('加载失败', 'error');
            return false;
        }
    }
}

// GameMap类（临时定义，应该从map.js导入）
class GameMap {
    constructor(mapData) {
        this.mapData = mapData;
        this.width = mapData.size.width;
        this.height = mapData.size.height;
        this.tiles = [];
        this.spawnPoints = [];
        this.portals = mapData.portals || [];
        this.tileTypes = mapData.tileTypes;
    }

    generate() {
        // 简化的地图生成逻辑
        this.tiles = [];
        for (let y = 0; y < this.height; y++) {
            this.tiles[y] = [];
            for (let x = 0; x < this.width; x++) {
                this.tiles[y][x] = 'grass';
            }
        }
        this.generateSpawnPoints();
    }

    generateSpawnPoints() {
        this.spawnPoints = [];
        const spawnCount = this.mapData.monsterCount || 10;
        
        for (let i = 0; i < spawnCount; i++) {
            const x = Math.floor(Math.random() * this.width);
            const y = Math.floor(Math.random() * this.height);
            this.spawnPoints.push({ x, y });
        }
    }

    getSpawnPoint() {
        if (this.spawnPoints.length === 0) return null;
        const index = Math.floor(Math.random() * this.spawnPoints.length);
        return this.spawnPoints[index];
    }

    isWalkable(x, y) {
        const tileX = Math.floor(x);
        const tileY = Math.floor(y);
        
        if (tileX < 0 || tileX >= this.width || tileY < 0 || tileY >= this.height) {
            return false;
        }
        
        if (this.tiles[tileY] && this.tiles[tileY][tileX] !== undefined) {
            const tileType = this.tiles[tileY][tileX];
            return this.tileTypes[tileType] ? this.tileTypes[tileType].walkable : false;
        }
        
        return false;
    }

    checkPortal(playerX, playerY) {
        if (!this.portals) return null;

        for (const portal of this.portals) {
            const distance = Math.sqrt(
                Math.pow(playerX / 32 - portal.x, 2) + 
                Math.pow(playerY / 32 - portal.y, 2)
            );
            
            if (distance < 2) {
                return portal;
            }
        }
        return null;
    }

    draw(ctx, camera) {
        const tileSize = GAME_CONSTANTS.TILE_SIZE;
        const startX = Math.floor(camera.x / tileSize);
        const startY = Math.floor(camera.y / tileSize);
        const endX = startX + Math.ceil(ctx.canvas.width / tileSize) + 1;
        const endY = startY + Math.ceil(ctx.canvas.height / tileSize) + 1;

        // 绘制背景
        ctx.fillStyle = this.mapData.background || '#2d5016';
        ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);

        // 绘制瓦片
        for (let y = startY; y < endY; y++) {
            for (let x = startX; x < endX; x++) {
                if (x >= 0 && x < this.width && y >= 0 && y < this.height) {
                    if (this.tiles[y] && this.tiles[y][x] !== undefined) {
                        const tileType = this.tiles[y][x];
                        const screenX = x * tileSize - camera.x;
                        const screenY = y * tileSize - camera.y;

                        if (this.tileTypes[tileType]) {
                            ctx.fillStyle = this.tileTypes[tileType].color;
                            ctx.fillRect(screenX, screenY, tileSize, tileSize);
                        }
                    }
                }
            }
        }

        // 绘制传送门
        this.drawPortals(ctx, camera);
    }

    drawPortals(ctx, camera) {
        if (!this.portals) return;

        this.portals.forEach(portal => {
            const screenX = portal.x * GAME_CONSTANTS.TILE_SIZE - camera.x;
            const screenY = portal.y * GAME_CONSTANTS.TILE_SIZE - camera.y;
            
            ctx.save();
            ctx.globalAlpha = 0.8;
            ctx.fillStyle = '#9C27B0';
            ctx.beginPath();
            ctx.arc(screenX + GAME_CONSTANTS.TILE_SIZE/2, screenY + GAME_CONSTANTS.TILE_SIZE/2, 
                   GAME_CONSTANTS.TILE_SIZE/2, 0, Math.PI * 2);
            ctx.fill();
            
            ctx.strokeStyle = '#E91E63';
            ctx.lineWidth = 3;
            ctx.stroke();
            ctx.restore();
        });
    }
}

// 添加全局测试函数
window.testUI = function() {
    console.log('=== UI测试开始 ===');
    
    // 测试按钮是否存在
    const buttons = ['inventory-button', 'character-button', 'skills-button', 'map-button'];
    buttons.forEach(id => {
        const btn = document.getElementById(id);
        console.log(`按钮 ${id}:`, btn ? '✅ 存在' : '❌ 不存在');
        if (btn) {
            console.log(`  - 是否可见:`, btn.offsetParent !== null ? '✅ 可见' : '❌ 隐藏');
            console.log(`  - 点击事件:`, btn.onclick ? '✅ 有绑定' : '❌ 无绑定');
        }
    });
    
    // 测试面板是否存在
    const panels = ['inventory-panel', 'character-panel', 'skills-panel', 'map-panel'];
    panels.forEach(id => {
        const panel = document.getElementById(id);
        console.log(`面板 ${id}:`, panel ? '✅ 存在' : '❌ 不存在');
        if (panel) {
            console.log(`  - 是否隐藏:`, panel.classList.contains('hidden') ? '✅ 隐藏' : '❌ 显示');
        }
    });
    
    console.log('=== UI测试结束 ===');
};

// 添加手动切换面板的测试函数
window.toggleTestPanel = function(panelId) {
    const panel = document.getElementById(panelId);
    if (panel) {
        panel.classList.toggle('hidden');
        console.log(`面板 ${panelId} 切换:`, panel.classList.contains('hidden') ? '隐藏' : '显示');
    } else {
        console.error(`面板 ${panelId} 不存在`);
    }
};

// 添加强制绑定事件的测试函数
window.forceBindEvents = function() {
    console.log('强制绑定UI事件...');
    
    const buttons = [
        { id: 'inventory-button', panel: 'inventory-panel' },
        { id: 'character-button', panel: 'character-panel' },
        { id: 'skills-button', panel: 'skills-panel' },
        { id: 'map-button', panel: 'map-panel' }
    ];
    
    buttons.forEach(({ id, panel }) => {
        const button = document.getElementById(id);
        if (button) {
            // 移除现有事件监听器
            button.onclick = null;
            
            // 绑定新的事件监听器
            button.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                console.log(`${id} 被点击`);
                
                const panelElement = document.getElementById(panel);
                if (panelElement) {
                    // 使用改进的状态检测逻辑
                    const hasHiddenClass = panelElement.classList.contains('hidden');
                    const isDisplayNone = getComputedStyle(panelElement).display === 'none';
                    const isReallyHidden = hasHiddenClass || isDisplayNone || panelElement.offsetParent === null;
                    
                    if (isReallyHidden) {
                        // 关闭其他面板
                        const allPanels = ['inventory-panel', 'character-panel', 'skills-panel', 'map-panel'];
                        allPanels.forEach(otherPanel => {
                            if (otherPanel !== panel) {
                                const otherPanelElement = document.getElementById(otherPanel);
                                if (otherPanelElement) {
                                    otherPanelElement.classList.add('hidden');
                                    otherPanelElement.classList.remove('force-show');
                                    otherPanelElement.style.display = 'none';
                                    otherPanelElement.style.visibility = 'hidden';
                                    otherPanelElement.style.opacity = '0';
                                }
                            }
                        });
                        
                        // 显示面板
                        panelElement.classList.remove('hidden');
                        panelElement.classList.add('force-show');
                        panelElement.style.display = 'block';
                        panelElement.style.visibility = 'visible';
                        panelElement.style.opacity = '1';
                        console.log(`${panel} 已显示`);
                    } else {
                        // 隐藏面板
                        panelElement.classList.add('hidden');
                        panelElement.classList.remove('force-show');
                        panelElement.style.display = 'none';
                        panelElement.style.visibility = 'hidden';
                        panelElement.style.opacity = '0';
                        console.log(`${panel} 已隐藏`);
                    }
                } else {
                    console.error(`面板 ${panel} 不存在`);
                }
            });
            
            console.log(`✅ ${id} 事件已绑定`);
        } else {
            console.error(`❌ ${id} 不存在`);
        }
    });
};

// 添加终极强制显示面板的测试函数
window.forceShowPanel = function(panelId) {
    console.log(`终极强制显示面板: ${panelId}`);
    const panel = document.getElementById(panelId);
    if (panel) {
        // 关闭其他面板
        const allPanels = ['inventory-panel', 'character-panel', 'skills-panel', 'map-panel'];
        allPanels.forEach(otherPanelId => {
            if (otherPanelId !== panelId) {
                const otherPanel = document.getElementById(otherPanelId);
                if (otherPanel) {
                    otherPanel.classList.add('hidden');
                    otherPanel.classList.remove('force-show');
                    otherPanel.removeAttribute('style');
                    otherPanel.style.cssText = 'display: none !important;';
                }
            }
        });
        
        // 完全重置目标面板
        panel.classList.remove('hidden');
        panel.classList.add('force-show');
        panel.removeAttribute('style');
        
        // 使用内联样式完全覆盖
        panel.style.cssText = `
            display: block !important;
            visibility: visible !important;
            opacity: 1 !important;
            z-index: 9999 !important;
            position: absolute !important;
            top: 50% !important;
            left: 50% !important;
            transform: translate(-50%, -50%) !important;
            width: ${panelId === 'map-panel' || panelId === 'character-panel' ? '700px' : '800px'} !important;
            height: 600px !important;
            background: linear-gradient(135deg, rgba(18, 23, 37, 0.98), rgba(25, 32, 48, 0.95)) !important;
            border-radius: 20px !important;
            color: #e1f5fe !important;
            border: 2px solid #64ffda !important;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5) !important;
            backdrop-filter: blur(10px) !important;
            overflow-y: auto !important;
            pointer-events: auto !important;
        `;
        
        console.log('面板完全重置完成，检查结果:');
        const isVisible = panel.offsetParent !== null && panel.offsetWidth > 0;
        console.log({
            offsetParent: panel.offsetParent,
            offsetWidth: panel.offsetWidth,
            offsetHeight: panel.offsetHeight,
            classList: Array.from(panel.classList),
            isVisible: isVisible,
            success: isVisible ? '✅ 成功显示' : '❌ 显示失败'
        });
    } else {
        console.error(`面板 ${panelId} 不存在`);
    }
};

// 重置所有面板状态的函数
window.resetAllPanels = function() {
    console.log('重置所有面板状态...');
    const allPanels = ['inventory-panel', 'character-panel', 'skills-panel', 'map-panel'];
    
    allPanels.forEach(panelId => {
        const panel = document.getElementById(panelId);
        if (panel) {
            // 完全重置面板状态
            panel.classList.remove('force-show');
            panel.classList.add('hidden');
            panel.style.cssText = 'display: none !important; visibility: hidden !important; opacity: 0 !important;';
            console.log(`✅ ${panelId} 已重置为隐藏状态`);
        }
    });
    
    console.log('所有面板已重置完成');
};

// 一键测试显示面板的函数
window.testShowPanel = function(panelId) {
    console.log(`=== 测试显示面板: ${panelId} ===`);
    
    // 先重置所有面板
    resetAllPanels();
    
    // 等待一下再显示目标面板
    setTimeout(() => {
        forceShowPanel(panelId);
    }, 200);
};

// 直接使用游戏管理器的方法
window.directShowPanel = function(panelId) {
    console.log(`=== 直接显示面板: ${panelId} ===`);
    if (window.gameApp && window.gameApp.gameManager) {
        window.gameApp.gameManager.showPanel(panelId);
    } else {
        console.error('游戏管理器未找到');
    }
};

window.directHidePanel = function(panelId) {
    console.log(`=== 直接隐藏面板: ${panelId} ===`);
    if (window.gameApp && window.gameApp.gameManager) {
        window.gameApp.gameManager.hidePanel(panelId);
    } else {
        console.error('游戏管理器未找到');
    }
};

// 🔧 紧急面板修复工具
window.emergencyPanelFix = function() {
    console.log('🚨 启动紧急面板修复...');
    
    // 检查所有面板是否存在
    const panels = ['inventory-panel', 'character-panel', 'skills-panel', 'map-panel'];
    const buttons = ['inventory-button', 'character-button', 'skills-button', 'map-button'];
    
    console.log('📋 检查面板和按钮状态:');
    panels.forEach(panelId => {
        const panel = document.getElementById(panelId);
        console.log(`${panelId}: ${panel ? '✅ 存在' : '❌ 不存在'}`);
    });
    
    buttons.forEach(buttonId => {
        const button = document.getElementById(buttonId);
        console.log(`${buttonId}: ${button ? '✅ 存在' : '❌ 不存在'}`);
    });
    
    // 重新绑定所有按钮事件
    console.log('🔗 重新绑定按钮事件...');
    buttons.forEach((buttonId, index) => {
        const button = document.getElementById(buttonId);
        const panelId = panels[index];
        
        if (button && document.getElementById(panelId)) {
            // 移除所有现有事件监听器
            button.replaceWith(button.cloneNode(true));
            const newButton = document.getElementById(buttonId);
            
            // 添加新的点击事件
            newButton.addEventListener('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                console.log(`🖱️ 点击了 ${buttonId}，显示 ${panelId}`);
                window.simpleShowPanel(panelId);
            });
            
            console.log(`✅ ${buttonId} 事件绑定完成`);
        }
    });
};

// 🎯 超简单面板显示
window.simpleShowPanel = function(panelId) {
    console.log(`🎯 超简单显示面板: ${panelId}`);
    
    // 1. 隐藏所有面板
    ['inventory-panel', 'character-panel', 'skills-panel', 'map-panel'].forEach(id => {
        const p = document.getElementById(id);
        if (p) {
            p.style.cssText = 'display: none !important;';
        }
    });
    
    // 2. 显示目标面板
    const panel = document.getElementById(panelId);
    if (!panel) {
        console.error(`❌ 面板 ${panelId} 不存在`);
        return;
    }
    
    // 3. 设置简单但有效的样式
    panel.style.cssText = `
        display: block !important;
        position: fixed !important;
        top: 50px !important;
        left: 50px !important;
        width: 800px !important;
        height: 600px !important;
        background-color: #1a2332 !important;
        color: white !important;
        border: 3px solid #00ff88 !important;
        border-radius: 15px !important;
        z-index: 99999 !important;
        padding: 20px !important;
        overflow: auto !important;
        box-shadow: 0 0 50px rgba(0, 255, 136, 0.3) !important;
    `;
    
    console.log(`✅ 面板 ${panelId} 显示完成`);
    
    // 4. 验证显示结果
    setTimeout(() => {
        const isVisible = panel.offsetWidth > 0 && panel.offsetHeight > 0;
        console.log(`📊 显示验证: ${isVisible ? '✅ 成功' : '❌ 失败'}`);
        console.log(`尺寸: ${panel.offsetWidth} x ${panel.offsetHeight}`);
    }, 100);
};

// 🧪 一键测试所有面板
window.testAllPanels = function() {
    console.log('🧪 测试所有面板...');
    const panels = ['inventory-panel', 'character-panel', 'skills-panel', 'map-panel'];
    let index = 0;
    
    function showNext() {
        if (index < panels.length) {
            const panelId = panels[index];
            console.log(`🔄 测试第 ${index + 1} 个面板: ${panelId}`);
            window.simpleShowPanel(panelId);
            index++;
            setTimeout(showNext, 2000); // 每2秒切换一个面板
        } else {
            console.log('✅ 所有面板测试完成');
        }
    }
    
    showNext();
};

export default GameManager;
